# -*- coding: utf-8 -*-
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields

def before_install():
    """应用安装前执行的操作"""
    pass

def after_install():
    """应用安装后执行的操作"""
    create_scrap_roles()
    create_custom_fields()

def create_scrap_roles():
    """创建余料管理相关角色"""
    roles = [
        {
            "doctype": "Role",
            "role_name": "Scrap Manager",
            "desk_access": 1,
            "is_standard": 1,
            "restrict_to_domain": None,
            "two_factor_auth": 0,
            "bypass_restrictions_if_missing": 0,
            "search_bar": 1,
            "notifications": 1,
            "description": "余料管理员，可以管理所有余料相关操作"
        },
        {
            "doctype": "Role",
            "role_name": "Scrap User",
            "desk_access": 1,
            "is_standard": 1,
            "restrict_to_domain": None,
            "two_factor_auth": 0,
            "bypass_restrictions_if_missing": 0,
            "search_bar": 1,
            "notifications": 1,
            "description": "余料用户，可以进行基本的余料操作"
        }
    ]
    
    for role_data in roles:
        if not frappe.db.exists("Role", role_data["role_name"]):
            role = frappe.get_doc(role_data)
            role.insert(ignore_permissions=True)
            frappe.db.commit()

def create_custom_fields():
    """创建自定义字段"""
    # 为User DocType添加余料仓库字段
    custom_fields = {
        "User": [
            {
                "fieldname": "default_scrap_warehouse",
                "label": "默认余料仓库",
                "fieldtype": "Link",
                "options": "Scrap Warehouse",
                "insert_after": "language",
                "description": "设置用户的默认余料仓库"
            }
        ]
    }
    
    create_custom_fields(custom_fields)